package org.yaac.client.widget;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 * @param <T>
 */
public abstract class BlockingAsyncCallback<T> implements AsyncCallback<T> {

	private static PopupPanel popup = new PopupPanel();

	private static final Label payload = new Label();
	
	// TODO : i18n?
	private static final String DEFAULT_MSG = "Processing...";
	
	static {
		popup = new PopupPanel(false);
		popup.setAnimationEnabled(true);
		popup.setGlassEnabled(true);
		popup.add(payload);
	}
	
	public static void block(String msg) {
		payload.setText(msg);
		popup.center();
	}
	
	public static void block() {
		block(DEFAULT_MSG);
	}

	public static void unblock() {
		popup.hide();
	}
	
	public BlockingAsyncCallback(String msg) {
		block(msg);
	}
	
	public BlockingAsyncCallback() {
		block();
	}
	
	@Override
	public void onSuccess(T result) {
		onBlockingCallSuccess(result);
		unblock();
	}

	@Override
	public void onFailure(Throwable caught) {
		onBlockingCallFailure(caught);
		unblock();
	}

	public abstract void onBlockingCallSuccess(T result);
	
	public abstract void onBlockingCallFailure(Throwable caught);
}
